package com.example.demo.common;

import lombok.SneakyThrows;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class MyClassFileTransformer implements ClassFileTransformer {

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        if (className.contains("MainController")) {
            final ClassPool classPool = ClassPool.getDefault();
            final CtClass clazz = classPool.get("com.example.demo.controller.MainController");
            CtMethod convertToAbbr = clazz.getDeclaredMethod("index");
            String methodBody = "return \"hello world【version2]\";";
            convertToAbbr.setBody(methodBody);
            // 返回字节码，并且detachCtClass对象
            byte[] byteCode = clazz.toBytecode();
            //detach的意思是将内存中曾经被javassist加载过的Date对象移除，如果下次有需要在内存中找不到会重新走javassist加载
            clazz.detach();
            return byteCode;
        }
        // 如果返回null则字节码不会被修改
        return null;
    }
}
